package com.ybkj.daijia.api.apirest;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Copyright (C) , 2012-2018 , 四川小咖科技有限公司
 *
 * @author xu
 * @version 1.0
 * @Date
 * @since 1.0.0
 */
@Controller
@RequestMapping("api/log4j")
public class Log4jController {

    /**
     * 动态修改日志级别
     *
     * @param packname 包名
     * @param levelStr 日志级别
     * @return
     */
    @RequestMapping(value = "setLevel", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> setLevel(String packname, String levelStr) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(packname)) {
            packname = "com.ybkj";
        }
        org.apache.log4j.Logger log4jLogger = LogManager.getLogger(packname);
        Level level = Level.toLevel(levelStr);
        log4jLogger.setLevel(level);
        map.put("code", 0);
        map.put("data", null);
        map.put("message", "设置日志级别：" + levelStr);
        return map;
    }

    /**
     * 获取日志级别
     *
     * @param packname
     * @return
     */
    @RequestMapping(value = "getLevel", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getLevel(String packname)
        throws IllegalAccessException, NoSuchFieldException {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(packname)) {
            packname = "com.ybkj";
        }
        org.apache.log4j.Logger log4jLogger = LogManager.getLogger(packname);
        Level level = log4jLogger.getLevel();
        Class clz = level.getClass().getSuperclass();
        String levelStr = null;

        Field field = clz.getDeclaredField("levelStr");
        field.setAccessible(true);
        levelStr = String.valueOf(field.get(level));
        map.put("code", 0);
        map.put("data", levelStr);
        return map;
    }
}
